import React, { useEffect, useState } from 'react';
import { Button, Form, Switch,Modal,Input, Space,message, Pagination, Select,Table  } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {getList,getDelete,getDeleteall,getType} from '../apis/news'
import '../assets/css/questions/questions.css';
import {baceUrl} from '../utils/config'
import Particulars from '../components/news/particulars'
import Newsadd from '../components/news/newsadd'
const { confirm } = Modal;
const Index: React.FC = () => {

  // 删除
  const del = (record:any) => {
    console.log(record)
    confirm({
      title: 'Do you Want to delete these items?',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除这条数据吗',
      onOk:async()=> {
        let res:any = await getDelete({id:record.id})
        console.log(res)
        if(res.errCode === 10000){
          message.success('删除成功')
          getData()
        }else{
          message.error(res.errMsg)
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  // 批量删除
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const dell = () => {
    confirm({
      title: 'Do you Want to delete these items?',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除此数据吗',
      onOk:async()=> {
        let res:any = await getDeleteall({ids:selectedRowKeys})
        console.log(res)
        if(res.errCode === 10000){
          message.success('删除成功')
          getData()
        }else{
          message.error(res.errMsg)
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
 
  //详情
  const [open, setOpen] = useState(false);

  const showModal = () => {
    setOpen(true);
  };

  const handleCancel = () => {
    setOpen(false);
  };
  // 开关
  // const onChange = (checked: boolean) => {
  //   console.log(`switch to ${checked}`);
  // };
  // 表格
  const columns: ColumnsType<any> = [
    {
      title: 'id',
      dataIndex: 'id',
      align:'center',
      key:'id'
    },
    {
      title: '类型',
      dataIndex: 'typename',
      align:'center',
      key: 'typename',
      render: (_,record) => (<div className='parti'>
        <div className='dan' onClick={showModal}>{record.typename}</div>
        <Modal
          open={open}
          onCancel={handleCancel}
          footer={[]}
        >
         <Particulars getOpen={record.id}></Particulars>
      </Modal>
      </div>)
    },{
      title: '标题',
      dataIndex: 'title',
      align:'center',
      key:'title'
    },
    {
      title: '图片',
      dataIndex: 'picture',
      key:"picture",
      align:'center',
      render:(_,record)=>(
        <Space size="middle">
            <img className='img' src={baceUrl + record.picture} alt="" />
        </Space>
    )
    },
    {
      title: '状态',
      dataIndex: 'type',
      align:'center',
      key:"type",
      render: (_,record) => (<div>
        {/* <Switch defaultChecked onChange={onChange}> */}
          {record.type===1?'开启':'关闭'}
        {/* </Switch> */}

      </div>)
    },
    {
      title: '发布时间',
      dataIndex: 'addtime',
      align:'center',
      key:"addtime"
    },
    {
      title: '发布人',
      dataIndex: 'edituser',
      align:'center',
      key:"addtime"
    },
    {
      title: '操作',
      dataIndex: 'id',
      align:'center',
      render: (_,record) => (<div>
        <Button type="primary" onClick={()=>getAdd(record)}>修改</Button>
        <Button className='botton' type="primary" danger onClick={()=>del(record)}>删除</Button>
      </div>)
    },
  ];

  //类型
  const [state,setState] = useState<any>([])
   const handleChange = async(value: string) => {
    console.log(`selected ${value}`);
  };
  const getState = async()=>{
    let res:any = await getType({})
    console.log(res)
    setState(res.data.list)
  }
  //查询
  interface Params{
    key:string,
    page:number,
    type:number,
    psize:number
  }
  const [params,setParams] = useState<Params>({key:'',page:1,type:state,psize:10})
  const onFinish = (values: any) => {
    console.log('Received values of form: ', values);
    setParams({...params,...values})
    console.log(params);
  };
  // 列表
  const [list,setList] = useState<any>([])
  const getData = async()=>{
    let res:any = await getList(params).catch(()=>{})
    console.log(res)
    if(res && res.errCode === 10000){
      setList(res.data.list)
      setTotal(res.data.counts)
    }
  }
   //分页
   const [total,setTotal] = useState(0)
   const changePagination = (page:any,pSize:any)=>{
       setParams({...params, page, psize: pSize})
   }
  // 添加
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [newadd,setNewadd] = useState({})
  const getAdd = (val?:any) => {
    setNewadd(val)
    setIsModalOpen(true);
  };
  const handleCancels = () => {
    setIsModalOpen(false);
    getData()
  };
  //调用
  useEffect(()=>{
    getData()
    getState()
  },[params])
  return (
    <div className="questions">
      <div className="header">
          <span className="title">公告列表</span>
      </div>
      <div className="top">
      <Form name="complex-form" onFinish={onFinish} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
      <div className="topTop">
        <Form.Item label="新闻" name="key">
            <Input placeholder="新闻名" />
        </Form.Item>
        <Form.Item label="公告类型" name="type">
          <Select
            placeholder="请选择"
            style={{ width: 120 }}
            onChange={handleChange}
            allowClear
            fieldNames={{label:'name',value:'id'}}
            options={state}
          />
        </Form.Item>
        <div className="bottomRight">
          <Button type="primary" htmlType="submit">查询</Button>
        </div>
      </div>
      </Form>
      </div>
      <div className="center">
        <Button className='newAdd' type="primary" onClick={()=>getAdd({id:0})}>添加</Button>
        {
          isModalOpen &&
          <Newsadd 
            isModalOpen={isModalOpen}
            newadd={newadd}
            handleCancels ={handleCancels} >
            
          </Newsadd>
        }
        <Button type="primary" danger onClick={dell}>批量删除</Button>
      </div>
      <div className="table">
        <Table rowKey="id" rowSelection={rowSelection} columns={columns} dataSource={list} pagination={false} />
      </div>
      <div className="Newcenter">
        <Pagination
            total={total}
            current={params.page}
            defaultCurrent={params.page}
            defaultPageSize={params.psize}
            showSizeChanger
            showQuickJumper
            pageSizeOptions={[10,15,20,40]}
            onChange={changePagination}
            showTotal={total => `共${total}条`}
        />
      </div>
    </div>
  );
};
export default Index;
